package com.ordos.recruit.module.dict.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ordos.recruit.module.dict.entity.DictionaryItemDto;
import com.ordos.recruit.module.dict.entity.DictionaryItemPo;
import com.ordos.recruit.module.dict.mapper.DictMapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 字典Service
 *
 * @author jin
 */
@Service
public class DictService {

    private final DictMapper dictMapper;

    private final Map<String, Map<String, DictionaryItemPo>> dictCache = new HashMap<>();

    public DictService(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    public List<DictionaryItemPo> getDictByDid(String did) {
        Map<String, DictionaryItemPo> valMap = dictCache.get(did);
        if (CollUtil.isNotEmpty(valMap)) {
            ArrayList<DictionaryItemPo> dictList = new ArrayList<>(valMap.values());
            dictList.sort((o1, o2) -> {
                Integer o1IntVal = o1.getSort();
                Integer o2IntVal = o2.getSort();
                if (o1IntVal == null) {
                    o1IntVal = 99999;
                }
                if (o2IntVal == null) {
                    o2IntVal = 99999;
                }
                return o1IntVal.compareTo(o2IntVal);
            });
            return dictList;
        }
        return new ArrayList<>();
    }

    public DictionaryItemPo getDictByCode(DictionaryItemDto dictionaryItemDto) {
        String dId = dictionaryItemDto.getCodeType();
        String code = dictionaryItemDto.getCode();

        if (CharSequenceUtil.isBlank(dId) || CharSequenceUtil.isBlank(code)) {
            return null;
        }

        Map<String, DictionaryItemPo> dictMap = dictCache.get(dId);
        if (CollUtil.isEmpty(dictMap)) {
            return null;
        }

        //获取值
        return dictMap.get(code);
    }

    public void refreshDict() {
        //获取字典数据列表
        List<DictionaryItemPo> dictList = dictMapper.selectList(new LambdaQueryWrapper<>());
        if (CollUtil.isEmpty(dictList)) {
            return;
        }
        dictList.forEach(dictPo -> {
            //获取当前类型.
            String dId = dictPo.getDId();
            if (CharSequenceUtil.isNotBlank(dId)) {
                //获取缓存中的list
                Map<String, DictionaryItemPo> cacheDictMap = dictCache.computeIfAbsent(dId, k -> new HashMap<>());
                cacheDictMap.put(dictPo.getCode(), dictPo);
            }
        });
    }

    @Scheduled(initialDelay = 1000, fixedDelay = 120000)
    public void refreshDictScheduled() {
        refreshDict();
    }

}
